<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api';

import { ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { Button, Card, message, Modal, Tree } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteUser,
  getDeptList,
  getUserList,
  resetPassword,
  updateUser,
} from '#/api/system';
import { $t } from '#/locales';

import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

// 部门树相关状态
const deptTreeData = ref<any[]>([]);
const selectedDeptId = ref<null | number>(null);

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    submitOnChange: true,
  },
  gridOptions: {
    columns: useColumns(onActionClick, onStatusChange),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          // 如果选择了部门，添加到查询条件
          const queryParams = {
            page: page.currentPage,
            page_size: page.pageSize,
            ...formValues,
          };

          if (selectedDeptId.value) {
            queryParams.dept_id = selectedDeptId.value;
          }

          return await getUserList(queryParams);
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: true,
      search: true,
      zoom: true,
    },
  } as VxeTableGridOptions<SystemUserApi.User>,
});

// 加载部门树数据
async function loadDeptTree() {
  deptTreeData.value = await getDeptList({ status: 1 });
}
// 初始化加载部门树
loadDeptTree();

// 部门树节点点击事件
function onDeptTreeSelect(selectedKeys: (number | string)[]) {
  selectedDeptId.value =
    selectedKeys.length > 0 ? Number(selectedKeys[0]) : null;
  // 刷新用户列表
  onRefresh();
}

function onActionClick(e: OnActionClickParams<SystemUserApi.User>) {
  switch (e.code) {
    case 'delete': {
      onDelete(e.row);
      break;
    }
    case 'edit': {
      onEdit(e.row);
      break;
    }
    case 'resetPassword': {
      onResetPassword(e.row);
      break;
    }
  }
}

function confirm(content: string, title: string) {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      content,
      onCancel() {
        reject(new Error('已取消'));
      },
      onOk() {
        resolve(true);
      },
      title,
    });
  });
}

/**
 * 状态开关即将改变
 */
async function onStatusChange(newStatus: number, row: SystemUserApi.User) {
  const status: Recordable<string> = {
    0: '禁用',
    1: '启用',
  };
  try {
    await confirm(
      `你要将${row.username}的状态切换为 【${status[newStatus.toString()]}】 吗？`,
      `切换状态`,
    );
    await updateUser({ ...row, status: newStatus as 0 | 1 });
    return true;
  } catch {
    return false;
  }
}

function onEdit(row: SystemUserApi.User) {
  formDrawerApi.setData(row).open();
}

async function onDelete(row: SystemUserApi.User) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
    key: 'action_process_msg',
  });

  await deleteUser(row.id)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.name]),
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
}

async function onResetPassword(row: SystemUserApi.User) {
  await confirm(
    `确定要重置用户 "${row.username}" 的密码吗？重置后密码为: 123456`,
    '重置密码',
  );

  const hideLoading = message.loading({
    content: '正在重置密码...',
    duration: 0,
    key: 'reset_password_msg',
  });

  await resetPassword(Number(row.id))
    .then(() => {
      message.success({
        content: '重置密码成功',
        key: 'reset_password_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
}

function onRefresh() {
  gridApi.query();
}

function onCreate() {
  formDrawerApi.setData({}).open();
}
</script>

<template>
  <Page auto-content-height>
    <FormDrawer @success="onRefresh" />

    <div class="flex h-full gap-2">
      <!-- 左侧部门树 -->
      <div class="w-64 flex-shrink-0">
        <Card
          class="h-full"
          :body-style="{
            padding: '12px',
            height: 'calc(100vh - 200px)',
            overflow: 'auto',
          }"
        >
          <Tree
            v-if="deptTreeData.length > 0"
            :show-line="true"
            :tree-data="deptTreeData"
            :default-expand-all="true"
            :selectable="true"
            :field-names="{ title: 'name', key: 'id' }"
            @select="onDeptTreeSelect"
          />
          <div v-else class="py-4 text-center text-gray-500">
            {{ $t('common.noData') }}
          </div>
        </Card>
      </div>

      <!-- 右侧用户列表 -->
      <div class="min-w-0 flex-1">
        <Grid :table-title="$t('system.user.list')">
          <template #toolbar-tools>
            <Button type="primary" @click="onCreate">
              <Plus class="size-5" />
              {{ $t('ui.actionTitle.create', [$t('system.user.name')]) }}
            </Button>
          </template>
        </Grid>
      </div>
    </div>
  </Page>
</template>
